﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using asMeishi.web.Models;

using publicLibrary;

namespace asMeishi.web.Controllers
{
    public class foodController : Controller
    {
        //
        // GET: /item/
        [authorityFilter(actionEnum.manage, actionTypeEnum.str)]
        public ActionResult Index()
        {
            foodC ic = new foodC();
            ViewData.Model = ic.db.query.ToList();

            return View();
        }

        //
        // GET: /item/Details/5

        public ActionResult Detail(string id,string type)
        {
            if (string.IsNullOrWhiteSpace(id)) { return Content(""); };

            foodC ic = new foodC();
            food item = ic.getById(id);

            if (type == "json")
            {
                return Json(item, JsonRequestBehavior.AllowGet);
            }
            else
            {
                ViewData.Model = item;
                DataSession<MongoDataContext, user> _userdb = userC.getDB();
                var impress = ic.getImpress(id);
                var result = (from c in impress //第一个表
                              join u in _userdb.query //第二个表
                              on c.userId equals u.Id //条件
                              into uDef //默认值处理
                              from uD in uDef.DefaultIfEmpty(userC.guestUser)
                              select new Object[] { c, uD }).ToList(); //返回
                ViewBag.impressUser = result;

                historyC<food> hc = new historyC<food>(item);

                ViewBag.history = hc.get();

                return View();
            }
        }



        //
        // GET: /item/Edit/5

        public ActionResult Edit(string id)
        {
            foodC ic = new foodC();
            ViewData.Model = ic.getById(id);

            return View();
        }

        //
        // POST: /item/Edit/5

        [HttpPost]
        public ActionResult Edit(string id, FormCollection collection)
        {
            food _item;
            foodC ic = new foodC();

            try
            {
                // TODO: Add update logic here

                if (string.IsNullOrWhiteSpace(id))
                {
                    _item = new foodC().createDefault();
                }
                else
                {
                    _item = ic.getById(id);
                }


                TryUpdateModel(_item);
                ic.save(_item);

                // TODO: Add update logic here
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        [HttpPost]
        public ActionResult Ajax_revise(string id, string name, string value) {

            foodC fc = new foodC();
            food f = fc.getById(id);
            switch (name)
            {
                case "foodName":
                    f.name = value;
                    break;
                case "foodIntro":
                    f.intro = value;
                    break;
                case "foodPrice":
                    try
                    {
                        f.price = Convert.ToDouble(value);
                    }
                    catch { }
                    break;
                default:
                    break;
            }
            f.lastDatatime = DateTime.Now;
            fc.save(f);

            //用户积分动作
            //userJF.up
            //用户积分动作end

            //用户减权限数
            //用户减权限数

            //日志
            historyC<shop>.Add(f.Id, name, historyTypeEnum.修改, null, userC.loginUser);
            //日志
            return Content(AjaxCallBackInfo.jsonOk());
        }

        public ActionResult detailImpress(string id, string type)
        {
            if (string.IsNullOrWhiteSpace(id)) { return Content(""); };

            foodC ic = new foodC();
            food item = ic.getById(id);
            //item.userName = item.getUserName();

            if (type == "json"){
                return Json(item, JsonRequestBehavior.AllowGet);
            }
            else {
                ViewData.Model = item;
                DataSession<MongoDataContext,user> _userdb = userC.getDB();
                var impress = ic.getImpress(id);
                var result = (from c in impress //第一个表
                             join u in _userdb.query //第二个表
                             on c.userId equals u.Id //条件
                             into uDef //默认值处理
                             from uD in uDef.DefaultIfEmpty(userC.guestUser)
                             select new Object[] { c, uD }).ToList(); //返回
                ViewBag.impressUser = result;

                return View();
            }
        }
        public ActionResult getImpression(string id, string type = "json")
        {
            foodC ic = new foodC();
            food item = ic.getById(id);
;
            return Json(ic.getImpress(id), JsonRequestBehavior.AllowGet);
        }
        public ActionResult delImpression(string id, string impressId)
        {
            try
            {
                foodC ic = new foodC();
                food item = ic.getById(id);
                ic.delImpress(item, impressId,userC.loginUser);

                return Content(AjaxCallBackInfo.jsonOk());
            }
            catch (Exception e) { return Content(AjaxCallBackInfo.jsonError()); }
        }
        [HttpPost]
        public ActionResult addImpression(string id,FormCollection fc)
        {
            try
            {
                foodC ic = new foodC();
                food food = ic.getById(id);
                impression imp = ic.addImpress(ref food, fc["content"],Convert.ToInt32(fc["foodGrade"]), userC.loginUser);

                return Content(AjaxCallBackInfo.jsonOk(imp.Id.ToString()));
            }
            catch (Exception e) { return Content(AjaxCallBackInfo.jsonError()); }
        }

        [HttpPost]
        [authorityFilter(actionEnum.upFile)]
        public ActionResult Ajax_addPic()
        {
            foodC fc = new foodC();
            HttpFileCollectionBase files = Request.Files;
            string foodId = Request.Params.Get("Id");

            food f = fc.getById(foodId);
            if (f == null) { return Content(AjaxCallBackInfo.jsonError("未找到目标"));  };

            if (string.IsNullOrEmpty(foodId) || files.Count == 0) { return Content("error"); }
            string fileName = fc.addPic(ref f, files[0]);

            //增加历史记录
            if (fileName != null)
            {
                fc.save(f);
                historyC<food>.Add(f.Id, "图片", historyTypeEnum.添加, fileName, userC.loginUser);
            }

            //返回
            return Content(AjaxCallBackInfo.jsonOk());

        }

    }

}
